<template>
  <div class="py-2">
    <el-space>
      <span class="font-bold">分档金额</span>
      <el-button :icon="Plus" circle size="small" @click="handleAdd" />
    </el-space>
  </div>
  <el-form :model="formState" ref="formRef">
    <el-row :gutter="20" class="mb-1">
      <el-col :span="6">
        <div class="text-center p-2">评分下限（含）</div>
      </el-col>
      <el-col :span="6">
        <div class="text-center p-2">评分上限</div>
      </el-col>
      <el-col :span="4">
        <div class="text-center p-2">补贴比例</div>
      </el-col>
      <el-col :span="6">
        <div class="text-center p-2">补贴金额</div>
      </el-col>
    </el-row>
    <el-row :gutter="20" v-for="(item, index) in formState.tieredAmounts" :key="index">
      <el-col :span="6">
        <el-form-item
          label=""
          :rules="createMinimumScoreRules(index)"
          :prop="'tieredAmounts.' + index + '.minimumScore'"
        >
          <el-input v-model="item.minimumScore" placeholder="" :disabled="index !== 0" />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item
          label=""
          :rules="createMaximumScoreRules(index)"
          :prop="'tieredAmounts.' + index + '.maximumScore'"
        >
          <el-input v-model="item.maximumScore" placeholder="" />
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item
          label=""
          :rules="createSubsidyRatioRules(index)"
          :prop="'tieredAmounts.' + index + '.subsidyRatio'"
        >
          <el-input v-model="item.subsidyRatio" placeholder="" :disabled="!!item.subsidyAmount" />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item
          label=""
          :rules="createSubsidyAmountRules(index)"
          :prop="'tieredAmounts.' + index + '.subsidyAmount'"
        >
          <el-input v-model="item.subsidyAmount" placeholder="" :disabled="!!item.subsidyRatio" />
        </el-form-item>
      </el-col>
      <el-col :span="2" v-if="index !== 0 && index === formState.tieredAmounts.length - 1">
        <el-button :icon="SemiSelect" circle @click="handleRemove(index)" />
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useId, type FormInstance } from 'element-plus'
import { SemiSelect, Plus } from '@element-plus/icons-vue'

const visible = inject('visible')

interface TieredAmount {
  id?: string | null
  minimumScore?: number | null
  maximumScore?: number | null
  subsidyRatio?: number | null
  subsidyAmount?: number | null
}

const formRef = ref<FormInstance>()
const formState = reactive({
  tieredAmounts: [] as TieredAmount[]
})

const createMinimumScoreRules = (index: number) => {
  const validator = (_rule, value, callback) => {
    // 必填校验
    if (!value && index !== 0) {
      return callback(new Error('请输入'))
    }

    // 格式校验
    if (value && !/^(0|[1-9]\d*)(\.\d{1,})?$/.test(value)) {
      return callback(new Error('请输入正确的数值'))
    }

    // 当前行的下限与当前行的上限校验
    // @ts-ignore
    const maximumScore = formState.tieredAmounts[index].maximumScore
    console.log('createMinimumScoreRules========', value > maximumScore)
    if (value && maximumScore && Number(value) > Number(maximumScore)) {
      return callback(new Error('不能大于评分上限'))
    }
    // 重置当前行的上限校验
    formRef.value?.clearValidate(['tieredAmounts.' + index + '.maximumScore'])

    callback()
  }
  return [{ validator, trigger: 'change' }]
}

const createMaximumScoreRules = (index: number) => {
  const validator = (_rule, value, callback) => {
    const size = formState.tieredAmounts.length
    // 必填校验
    if (!value && index !== size - 1) {
      return callback(new Error('请输入'))
    }

    // 格式校验
    if (value && !/^(0|[1-9]\d*)(\.\d{1,})?$/.test(value)) {
      return callback(new Error('请输入正确的数值'))
    }

    // 当前行的上限与当前行的下限校验
    // @ts-ignore
    const minimumScore = formState.tieredAmounts[index].minimumScore
    console.log('createMaximumScoreRules========', minimumScore, value)
    if (value && minimumScore && Number(value) < Number(minimumScore)) {
      return callback(new Error('不能小于评分下限'))
    }
    // 重置当前行的下限校验
    formRef.value?.clearValidate(['tieredAmounts.' + index + '.minimumScore'])

    // 设置下一行的下限
    if (index !== size - 1) {
      formState.tieredAmounts[index + 1].minimumScore = value
      formRef.value?.clearValidate(['tieredAmounts.' + index + 1 + '.minimumScore'])
    }
    callback()
  }
  return [{ validator, trigger: 'change' }]
}

const createSubsidyRatioRules = (index: number) => {
  const validator = (_rule, value, callback) => {
    // @ts-ignore
    const subsidyRatio = formState.tieredAmounts[index].subsidyRatio

    // 必填校验
    if (!value && !subsidyRatio) {
      return callback(new Error('补贴比例和补贴金额必须输入一个'))
    }

    // 格式校验
    if (value && !/^(0|[1-9]\d*)(\.\d{1,})?$/.test(value)) {
      return callback(new Error('请输入正确的数值'))
    }

    // 重置当前行的下限校验
    formRef.value?.clearValidate(['tieredAmounts.' + index + '.subsidyAmount'])

    callback()
  }
  return [{ validator, trigger: 'change' }]
}

const createSubsidyAmountRules = (index: number) => {
  const validator = (_rule, value, callback) => {
    // @ts-ignore
    const subsidyAmount = formState.tieredAmounts[index].subsidyAmount

    // 必填校验
    if (!value && !subsidyAmount) {
      return callback(new Error('补贴比例和补贴金额必须输入一个'))
    }

    // 格式校验
    if (value && !/^(0|[1-9]\d*)(\.\d{1,})?$/.test(value)) {
      return callback(new Error('请输入正确的数值'))
    }

    // 重置当前行的下限校验
    formRef.value?.clearValidate(['tieredAmounts.' + index + '.subsidyRatio'])

    callback()
  }
  return [{ validator, trigger: 'change' }]
}

const handleAdd = () => {
  const size = formState.tieredAmounts.length
  const prevItem = size > 0 ? formState.tieredAmounts[size - 1] : null

  formState.tieredAmounts.push({
    id: useId().value,
    minimumScore: prevItem?.maximumScore || null,
    maximumScore: null,
    subsidyRatio: null,
    subsidyAmount: null
  })
}

const handleRemove = (index: number) => {
  formState.tieredAmounts.splice(index, 1)
  // 重置上一行的上限校验
  if (index !== 0) {
    formRef.value?.clearValidate(['tieredAmounts.' + (index - 1) + '.maximumScore'])
  }
}

watch(
  () => visible,
  (value) => {
    if (value) {
      handleAdd()
    } else {
      formRef.value?.resetFields()
    }
  },
  { immediate: true }
)

defineExpose({
  form: formRef,
  state: formState
})
</script>
